import { useState } from 'react';
import { useDialog } from '../../common/hooks/useDialog';
import { useData } from '../../common/formData';
import { getEvents } from '../../api/event';
import { getSmallMap } from '../../common/map';
import moment from 'moment';
import '../../../gis/utils/Draw';
import { createDraw } from '../../../gis/utils/Draw';
import { DOCNAME, ip, port } from '../../constants';
import Point from '../../../gis/utils/Point';
import { Query } from '../../../gis/utils/Query';
import { putEvents } from '../../api/event';
import { deleteFeature } from '../../../gis/utils/delFeature';
export function useEvent() {
  const [edata, setEdata] = useState([]);
  const [status, setStatus] = useState(1);
  // 控制表单对话框显隐
  const [visible, showDialog, closeDialog] = useDialog();
  // 地图对话框中的地图
  const [modalMap, setModalMap] = useState();
  const initMap = () => {
    setModalMap(getSmallMap({ id: 'map-modal' }));
  };
  // 控制地图对话框的显隐
  const [visibleMap, showMap, closeMap] = useDialog();
  // 定义一个用于记录事件id的状态
  const [eId, setEId] = useState();
  // 表单提交事件
  const [memory, setMemory] = useState();
  const submit = (data) => {
    setMemory(data);
    closeDialog();
    showMap();
  };
  //根据title获取图层
  const getLayer = (map, title) => {
    return map
      .getLayers()
      .getArray()
      .find((item) => item.values_.title == title);
  };
  // 开始添加事件
  const submitMap = () => {
    let layer = getLayer(modalMap, 'draw');
    let source = layer.getSource();

    let keys = [
      '事件编号',
      '事件类型',
      '事件等级',
      '发生时间',
      '发生地点',
      '车牌号',
      '驾驶员',
      '处理状态',
    ];
    let types = [
      'string',
      'string',
      'short',
      'string',
      'string',
      'string',
      'string',
      'short',
    ];
    let values = [
      eId,
      memory.type,
      memory.level,
      memory.time._i,
      memory.addr,
      '',
      '',
      0,
    ];
    let attr = keys.map((item, index) => {
      return { key: item, type: types[index], value: values[index] };
    });
    // 开始画点
    let draw = createDraw({
      source,
      callback: (e) => {
        let position = e.feature.getGeometry().getCoordinates();
        let service = {
          docName: DOCNAME,
          layerID: 2,
          docLayer: modalMap.getLayers().getArray()[1],
        };
        Point.add(
          {
            position,
            attr,
            service,
          },
          (data) => {
            if (data.succeed) {
              alert('添加点要素成功！');
              modalMap.getLayers().getArray()[1].refresh();
              // 查询到添加的点
              Query.queryBySql({
                where: `事件编号='${eId}'`,
                service: {
                  docName: DOCNAME,
                  layerId: 2,
                  docLayer: modalMap.getLayers().getArray()[1],
                },
                callback: (e) => {
                  let fids = e.SFEleArray.map((item) => item.FID);
                  new Promise((res) => {
                    res();
                  }).then(() => {
                    source.clear();
                    modalMap.interactions.pop();
                  });
                  let fidStr = fids.join(',');
                  putEvents(eId, status, memory, fidStr).then((res) => {
                    if (res.data.code != 0) {
                      // 数据库更新失败删除已添加的点
                      deleteFeature({ ...service, fids }, (e) => {});
                    }
                    getEData(1, 40);
                  });
                },
              });
            } else {
              alert('添加点要素失败！');
            }
          }
        );
      },
    });
    modalMap.addInteraction(draw);
  };
  // 回显数据
  const [initialValues, setInitialValues] = useState();
  const [defaultFileList, setDefaultFileList] = useState([]);
  // 初始化表单
  let [formData] = useData({});
  const getEData = (page, size) => {
    getEvents({ page, size }).then((res) => {
      const edata = res.data.result;
      setEdata([...edata]);
    });
  };
  // 打开表单
  const Toggle = (status, id, index) => {
    if (status == 0) {
      putEvents(id, status).then((res) => {
        getEData(1, 40);
      });
      return;
    }
    // 根据id来回显数据
    edata.forEach((item) => {
      if (item.event_id == id) {
        setDefaultFileList([{ url: item.event_imgurl }]);
        setInitialValues({
          level: item.event_level,
          type: item.event_type,
          img: item.event_imgurl,
          content: item.event_descri,
          time: moment('1981-12-21 07:24:20', 'YYYY/MM/DD h:mm:ss'),
          addr: item.event_addr,
          sign: item.event_sign,
          radius: item.event_radius,
        });
      }
    });
    setEId(id);
    showDialog();
    setStatus(status);
  };
  return {
    edata,
    setEdata,
    visible,
    showDialog,
    closeDialog,
    eId,
    setEId,
    submit,
    initialValues,
    setInitialValues,
    defaultFileList,
    setDefaultFileList,
    formData,
    getEData,
    Toggle,
    visibleMap,
    showMap,
    closeMap,
    modalMap,
    initMap,
    submitMap,
  };
}
